package com.chatdating.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chatdating.entity.Comment;
import com.chatdating.entity.Post;
import com.chatdating.entity.dto.AdminPostDto;
import com.chatdating.mapper.PostMapper;
import com.chatdating.service.CommentService;
import com.chatdating.service.LikeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chatdating.service.PostService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private CommentService commentService;

    @Autowired
    private LikeService likeService;


    @Override
    public List<Post> findById(Long id) {
        return postMapper.findById(id);
    }

    @Value("${app.upload-dir}")
    private String uploadDir;

    @Override
    public Post getPostWithDetails(Long id) {
        Post post = baseMapper.selectById(id);
        if(post != null) {
            // 添加评论
            post.setComments(commentService.getCommentsByPostId(id));
            //添加评论数
            post.setCommentCount(commentService.getCommentCountByPostId(id));
            // 添加点赞数
            post.setLikeCount(likeService.getLikeCount(id));
            // 添加评论数
            post.setCommentCount((int)commentService.count(
                    new QueryWrapper<Comment>().eq("post_id", post.getId())
            ));
        }
        return post;
    }

    @Override
    public Page<Post> pagePosts(Page<Post> page, String keyword) {
        QueryWrapper<Post> queryWrapper = new QueryWrapper<>();

        // 添加搜索条件
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.like("content", keyword);
        }

        // 按创建时间倒序
        queryWrapper.orderByDesc("create_time");

        // 执行分页查询
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    public PageInfo<AdminPostDto> delPostList(Integer pageNum, Integer pageSize, String uname, Integer id) {
        PageHelper.startPage(pageNum, pageSize);
        List<AdminPostDto> list = postMapper.delPostList(uname, id);
        return new PageInfo<>(list);
    }

    @Override
    public void adminRemoveById(int id) {
        postMapper.adminRemoveById(id);
    }

    @Override
    public void adminRecoverPostById(int id) {
        postMapper.adminRecoverPostById(id);
    }

    @Override
    public Post getPostWithByid(Long id) {
        Post post = postMapper.selectPostById(id);
        if(post != null) {
            // 添加评论
            post.setComments(commentService.getCommentsByPostId(id));
            //添加评论数
            post.setCommentCount(commentService.getCommentCountByPostId(id));
            // 添加点赞数
            post.setLikeCount(likeService.getLikeCount(id));
            // 添加评论数
            post.setCommentCount((int)commentService.count(
                    new QueryWrapper<Comment>().eq("post_id", post.getId())
            ));
        }
        return post;
    }

    @Override
    public Page<Post> getPagePostsByAuthorId(Page<Post> page, Integer authorId, String keyword) {
        QueryWrapper<Post> queryWrapper = new QueryWrapper<>();

        //添加搜索条件
        queryWrapper.eq("author_id", authorId);
        queryWrapper.eq("deleted", 0);

        // 添加搜索条件
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.like("content", keyword);
        }

        // 按创建时间倒序
        queryWrapper.orderByDesc("create_time");

        // 执行分页查询
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    public List<String> uploadImages(MultipartFile[] images) {
        List<String> urls = new ArrayList<>();
        if (images == null) {
            return urls;
        }

        for (MultipartFile image : images) {
            if (image != null && !image.isEmpty()) {
                try {
                    String url = uploadImage(image);
                    urls.add(url);
                } catch (IOException e) {
                    log.error("图片上传失败: {}");
                }
            }
        }
        return urls;
    }

    @Override
    public PageInfo<AdminPostDto> AdminPostList(Integer pageNum, Integer pageSize, String uname, Integer id) {
        PageHelper.startPage(pageNum, pageSize);
        List<AdminPostDto> list = postMapper.selectPostBy(uname, id);
        return new PageInfo<>(list);
    }

    private String uploadImage(MultipartFile file) throws IOException {
        // 验证文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            throw new IllegalArgumentException("仅支持图片文件上传");
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String fileName = UUID.randomUUID() + extension;

        // 创建目标路径
        Path targetPath = Paths.get(uploadDir, fileName);
        Files.createDirectories(targetPath.getParent());

        // 保存文件
        Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);

        // 返回访问URL
        return fileName; // 返回文件名，前端拼接完整URL
    }
}
